﻿/// <reference path="jquery-2.1.3.js" />


(function (window, undefined) {

    var $ = window.$, app = window.app;
    //保存表单
    window.app.saveForm = function (event, url) {
        var $button = $(event.currentTarget);
        var $form = $button.parent().prev(".modal-body").find("form"); //直接查找模态框的表单
        if ($form.length === 0) {
            $form = $("#modalcontent form");
        }
        if ($form.length === 0) {
            $form = $(".box-body form");
        }
        if ($form.length === 0) {
            window.app.message("怎么表单不对啊！");
        }

        if (false === $form.validate({ ignore: "" }).checkForm()) {
            if (event && event.preventDefault) {
                //阻止默认浏览器动作(W3C)  
                event.preventDefault();
                event.stopPropagation();
            } else {
                //IE中阻止函数器默认动作的方式   
                window.event.returnValue = false;
            }

            $form.valid();
            return false;
        }
        $.ajax({
            type: "POST",
            url: url,
            data: $form.serialize(),
            dataType: "json",
            success: function (data) {
                if (data.errors.length > 0) {
                    swal("出错啦！", data.errors, "error");
                    $button.button('reset');
                } else {
                    if (data.redirectToUrl == null || data.redirectToUrl.length === 0) {
                        //关闭对话框刷新数据列表

                        window.app.modalClose();
                        window.app.search();
                    } else if (data.redirectToUrl.indexOf("javascript:") >= 0) {
                        eval(data.redirectToUrl.substr(10, data.redirectToUrl.length - 10));
                    } else if (data.redirectToUrl != null && data.redirectToUrl.length > 0) {
                        //加载其他页面
                        window.app.modalClose();
                        window.app.loadUI(data.redirectToUrl);
                    }
                }
            },
            error: function (xmlHttpRequest, textStatus, errorThrown) {
                window.app.message("服务器异常。" + textStatus);
                $(event.target).button('reset');
            }
        });
    };
    //删除数据
    window.app.deleteItem = function (dataTable, url) {

        if ($("#" + dataTable).length === 0) {
            window.app.message("实现错误，列表Id给错。");
            return;
        }
        var ids = new Array();

        $("#" + dataTable + " tbody tr").each(function (x) {

            var checkbox;
            if ($(this).find(".checkColumn").length > 0) {
                checkbox = $(this).find(".checkColumn input");
            } else {
                checkbox = $(this).find("td:eq(0) input");
            }

            if (checkbox.length > 0 && checkbox.prop('checked')) {
                ids.push(checkbox.val());
            }
        });

        if (ids.length === 0) {
            window.app.message("请选中一项。");
            return;
        }

        swal({
            title: "请确认是否删除？",
            text: "您正在进行删除操作，该操作不可逆!",
            type: "warning",
            showCancelButton: true,
            confirmButtonClass: "btn-danger"
        }).then(function (isConfirm) {
            if (isConfirm === true) {
                $.ajax({
                    type: "POST",
                    url: url,
                    data: { "ids": ids },
                    dataType: "json",
                    success: function (data) {
                        if (data.errors.length > 0) {
                            swal("出错啦！", data.errors, "error");
                        } else {
                            //swal("已经删除", "你已经删除成功！", "success");
                            swal({
                                title: "已经删除",
                                text: "你已经删除成功",
                                type: "success",
                                timer: 2000
                            });
                            debugger;
                            if (data.redirectToUrl == null || data.redirectToUrl.length === 0) {
                                $('#' + dataTable).DataTable().ajax.reload();
                                $('#' + dataTable).find("thead th input").attr("checked", false);
                            } else if (data.redirectToUrl.indexOf("javascript:") >= 0) {
                                eval(data.redirectToUrl.substr(10, data.redirectToUrl.length - 10));
                            } else if (data.redirectToUrl != null && data.redirectToUrl.length > 0) {

                                window.app.modalClose();
                                window.app.loadUI(data.redirectToUrl); //加载其他页面
                            }
                        }
                    }
                });
            }
        });
    };
    //打开编辑界面
    window.app.showEditWindow = function (dataTable, url, button) {

        if ($("#" + dataTable).length === 0) {
            window.app.message("实现错误，列表Id给错。");
            return;
        }
        var ids = new Array();
        $("#" + dataTable + " tbody tr").each(function (x) {

            var checkbox = $(this).find(".checkColumn input");
            
            if (checkbox.length > 0 && checkbox.prop('checked')) {
                ids.push(checkbox.val());
            }
        });

        if (ids.length === 0) {
            window.app.message("请选中一项。");
            return;
        }
        if (ids.length > 1) {
            window.app.message("请只选中一项。");
            return;
        }
        $(button).attr("href", url + "?Id=" + ids[0]);
    }
    //加载界面
    window.app.loadUI = function (url) {
        $("#divMainContent").load(url, function (response, status, xhr) {
            //window.history.pushState(null, null, url);
            if ($.validator) {
                   $.validator.unobtrusive.parse($('#modalcontent form'));
            }
        });
    };
    //消息
    window.app.message = function (text) {
        swal({
            title: "",
            text: text,
            timer: 2000
        });
    };
    //刷新DataTable、搜索
    window.app.search = function () {
        $(".dataTable").each(function (index, item) {
            if (true === $(item).is(":visible")) {
                $(item).DataTable().ajax.reload();
            }
        });

    };
    //关闭窗口
    window.app.modalClose = function () {
        $("#ajaxModal .modal").modal("hide");
        $("#ajaxModal").remove();
        $(".modal-backdrop").remove();
    };
    //window.addEventListener('popstate', function (e) {

    //    if (location.pathname === "/") {

    //    } else {
    //        window.app.loadUI(location.pathname);
    //    }
    //});
}(window));

//搜索
var Search = window.app.search;

Request =
{
    QueryString: function (item) {
        var svalue = location.search.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)", "i"));
        return svalue ? svalue[1] : svalue;
    }
};
/**
 * 时间对象的格式化
 */
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(),    //day
        "H+": this.getHours(),   //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
        "f+": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (this.toString() === "Invalid Date") {
        return "";
    }
    //1970-01-01 08
    if (this.getFullYear() === 1970) {
        return "";
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            var str;

            if (RegExp.$1.length === 1) {
                str = o[k];
            } else if (RegExp.$1.length === 2) {
                str = ("00" + o[k]).substr(("" + o[k]).length);
            } else {
                str = ("000" + o[k]).substr(("" + o[k]).length);
            }


            format = format.replace(RegExp.$1, str);
        }
    }
    return format;
};